package com.prp.gwt.client.widgets.user.profile;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.prp.gwt.client.user.profile.ProfileListener;

public class PasswordPanel extends VerticalPanel {
	
	private PasswordTextBox oldPassword = new PasswordTextBox();
	private PasswordTextBox newPassword = new PasswordTextBox();
	private PasswordTextBox passwordConfirm = new PasswordTextBox();
	private final Grid grid = new Grid(3, 3);
	private HTML message = new HTML();

	public PasswordPanel() {
		grid.setHTML(0, 0, "旧密码");
		grid.setWidget(0, 1, oldPassword);
		grid.setHTML(1, 0, "新密码");
		grid.setWidget(1, 1, newPassword);
		grid.setHTML(2, 0, "确认新密码");
		grid.setWidget(2, 1, passwordConfirm);
		add(grid);
		
		HorizontalPanel panel = new HorizontalPanel();
		HTML reset = new HTML("<a>重置</a>");
		panel.add(reset);
		panel.add(message);
		panel.setSpacing(5);
		add(panel);
		
		reset.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				reset();
				clearErr();
				message.setText("");
			}
		});
	}
	
	private void clearErr(){
		grid.setHTML(0, 2, "");
		grid.setHTML(1, 2, "");
		grid.setHTML(2, 2, "");
	}
	
	public void reset(){
		oldPassword.setText("");
		newPassword.setText("");
		passwordConfirm.setText("");
		clearErr();
	}
	
	public void showSuccess(){
		message.setText("修改成功");
	}
	
	public void showError(){
		grid.setHTML(0, 2, "密码错误");
	}
	
	public boolean commit(){
		String op = oldPassword.getText();
		String np = newPassword.getText();
		String cp = passwordConfirm.getText();
		if(op.equals("")){
			grid.setHTML(0, 2, "请输入旧密码");
			return false;
		}
		if(np.equals("")){
			grid.setHTML(1, 2, "请输入新密码");
			return false;
		}
		if(cp.equals("")){
			grid.setHTML(2, 2, "请确认密码");
			return false;
		}
		if(!np.equals(cp)){
			grid.setHTML(1, 2, "请检查密码");
			return false;
		}
		clearErr();
		message.setText("");
		ProfileListener.getInstance().modifyPassword(op, np);
		return true;
	}
	
}
